package com.chuangjian.hire.sms.service.impl;

import com.chuangjian.hire.common.exceptionEnum.ApiExceptionEnum;
import com.chuangjian.hire.common.exption.ApiException;
import com.chuangjian.hire.sms.service.MailService;
import com.chuangjian.hire.users.dto.EmailDTO;
import com.chuangjian.hire.users.service.UsersService;
import com.chuangjian.hire.util.StringUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements MailService {

    @Resource
    JavaMailSender javaMailSender;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    UsersService usersService;

    @SneakyThrows
    public void sendMail(String from, String to, String subject, Map<String, Object> params) {
        // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setSubject(subject);
        Context context = new Context();
        context.setVariables(params);
        String text = templateEngine.process("template", context);
        mimeMessageHelper.setText(text, true);
        javaMailSender.send(mimeMessage);
    }

    @Override
    public String sendEmailCode(EmailDTO emailDTO) {
        String randomCode = StringUtil.getRandomCodeA(6);
        redisTemplate.opsForValue().set(emailDTO.getEmail(), randomCode, 2, TimeUnit.HOURS);
        HashMap<String, Object> map = new HashMap<>();
        map.put("msgCode", randomCode);
        sendMail("wangtk-cn@qq.com", emailDTO.getEmail(), "美工网 绑定邮箱", map);
        return randomCode;
    }

    @Override
    public Boolean verifyEmail(EmailDTO emailDTO) {
        String randomCode = redisTemplate.opsForValue().get(emailDTO.getEmail());
        if (!Objects.equals(emailDTO.getCode(), randomCode)) {
            throw new ApiException(ApiExceptionEnum.EMAIL_CODE_ERROR);
        }
        return usersService.bindEmail(emailDTO);
    }
}
